package cn.zxcoder.controller.login;


import cn.zxcoder.Tools.TokenUtil;
import cn.zxcoder.Tools.ToolUtil;
import cn.zxcoder.entity.login.Account;
import cn.zxcoder.entity.Res;
import cn.zxcoder.entity.login.Behavior;
import cn.zxcoder.service.IAccountService;
import cn.zxcoder.service.IBehaviorService;
import cn.zxcoder.service.IOrderService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Api(tags = "登录控制器")
@RequestMapping("/api")
@RestController
@Slf4j
public class LoginControlller {

    @Autowired
    IAccountService accountServiceIml;

    @Resource
    RedisTemplate redisTemplate;

    @Autowired
    IOrderService iOrderServiceIml;

    @Autowired
    IBehaviorService iBehaviorServiceImpl;

    @ApiOperation("具体的登录servlet")
    @PostMapping("/login")
    public Res login(HttpServletRequest request, HttpServletResponse response, @RequestParam String username, @RequestParam String password, @RequestParam String code ) {


        String remoteAddr = request.getRemoteAddr();
        String key = "code:" + remoteAddr;
//        String coding = ToolUtil.jedis.get(key);//验证码
        String coding = (String) redisTemplate.opsForValue().get(key);
        System.out.println("-------------------------");
        System.out.println("本身验证码是:"+coding);
        System.out.println("key:"+key);
        System.out.println("-------------------------");

        if (!code.equals(coding)) {
            return new Res(false,"验证码错误");
        }
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        HashMap<String, String> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        wrapper.allEq(map);
        Account one = accountServiceIml.getOne(wrapper);
        if (one == null) {
            return new Res(false, "账号或密码错误");
        } else {
            UpdateWrapper<Account> accountUpdateWrapper = new UpdateWrapper<>();
            accountUpdateWrapper.set("status", "N");
            accountUpdateWrapper.allEq(map);
            accountServiceIml.update(accountUpdateWrapper);//设置在线

            String data = JSON.toJSONString(one);



            System.out.println("登录成功");

            //防止重复登录
//            生成对应的token值
//            String token = ToolUtil.simpleUUID();
            String token = TokenUtil.sign(username, "" + one.getId());

            //记录到操作日志

            Behavior behavior = new Behavior();
            behavior.setTime(new Date());
            behavior.setType(0);
            behavior.setUserId(Integer.parseInt(TokenUtil.getId(token)));
            behavior.setUserName(username);
            boolean save = iBehaviorServiceImpl.save(behavior);
            if (!save) {
                log.error("保存日志失败");
            }


            System.out.println("生成对应的token值:" + token);
            //根据这个token存入到对应的jedis中去
//            ToolUtil.jedis.setex(token, 24 * 60 * 60, username);
//            ToolUtil.jedis.setex(username, 24 * 60 * 60, token);
//            redisTemplate.opsForValue().set(token, username,1, TimeUnit.DAYS);
            redisTemplate.opsForValue().set(username,token , 1,TimeUnit.DAYS);







//            if (ToolUtil.jedis.get("user:" + username) == null) {
//                ToolUtil.jedis.setex("user:" + username, 24 * 60 * 60, "{username:" + username + "password:" + password + "}");
//            } else {
//                return new Res(false, data, "不能重复登录");
//            }
            return new Res(true, data, "登录成功",token);

        }
    }

    @ApiOperation("具体的登录servlet")
    @DeleteMapping("/loginOut")
    public Res loginOut(HttpServletRequest request) {

        String token = request.getHeader("token");
        String username = TokenUtil.getName(token);
//        Account account = JSON.parseObject(token, Account.class);
//        Integer id = account.getId();
        UpdateWrapper<Account> wrapper = new UpdateWrapper<>();
        wrapper.eq("username", username);
        wrapper.set("status", "Y");


//        ToolUtil.jedis.del(account.getUsername());
        redisTemplate.delete(username);

        //记录到操作日志

        Behavior behavior = new Behavior();
        behavior.setTime(new Date());
        behavior.setType(1);
        behavior.setUserId(Integer.parseInt(TokenUtil.getId(token)));
        behavior.setUserName(TokenUtil.getName(token));
        boolean save = iBehaviorServiceImpl.save(behavior);
        if (!save) {
            log.error("保存日志失败");
        }

        boolean update = accountServiceIml.update(wrapper);
        return new Res(update, null, update ? "退出成果" : "退出失败");


    }



}
